<template>
    <div>
        <Spin fix v-if="isSpin3">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <div>导出附件加载中</div>
        </Spin>
        <Row :gutter="16">
            <i-col span="24">
                <Card dis-hover>
                    <Form ref="formCustom" :model="formInline" :label-width="100" >
                        <Row :gutter="16" class="query-form2" >
                            <i-col span="8">
                                <FormItem label="所属单位：">
                                    <!-- <Select v-model="formInline.orgId" filterable>
                                        <Option v-for="item in twoLevelOrgList" :value="item.orgId" :key="item.orgId">{{ item.orgName }}</Option>
                                    </Select> -->
                                    <cascaderDom ref="queryOrgCascader" @setOrgInfo="setOrgId" :setCurrentName="{value: formInline.orgId,label : formInline.orgName}"
                                     :rootOrgId="userInfo.companyId" class="query-form-el"
                                     :orgTree="true"></cascaderDom>
                                </FormItem>
                            </i-col>
                            <i-col span="8">
                                <FormItem label="当前年度：">
                                    <DatePicker v-model="formInline.inputYear"  type="year" placeholder="请选择投入年份" style="width: 100%" :clearable="false"></DatePicker>
                                </FormItem>
                            </i-col>
                            <i-col span="8">
                                <Button class="ivu-btn-query"  icon="md-search"  @click="queryAll">查询</Button>
                                <Button style="margin-left: 10px" class="ivu-btn-reset" @click="exportExcel">导出</Button>
								<Button @click="reset1" class="ivu-btn-reset" style="margin-left: 10px;">重置</Button>
                            </i-col>
                        </Row>
                    </Form>
                </Card>
            </i-col>
        </Row>
        <Row :gutter="16" style="margin-top: 15px">
            <i-col span="12">
                <Card dis-hover class="safety_title" :bordered=false>
                    近五年投入总数（万元）<span style="float: right">{{sumData.fiveYear}}</span>
                </Card>
            </i-col>
            <i-col span="12">
                <Card dis-hover class="safety_title" :bordered=false>
                    本年度投入总数（万元）<span style="float: right">{{sumData.nowYear}}</span>
                </Card>
            </i-col>
        </Row>
        <Row :gutter="16" style="margin-top: 15px">
            <i-col span="12">
                <Spin fix v-if="isSpin1">
                    <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
                    <div>视图加载中</div>
                </Spin>
                <div style="height: 337px; width: 100%" ref="container1"></div>
            </i-col>
            <i-col span="11">
                <Spin fix v-if="isSpin2">
                    <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
                    <div>视图加载中</div>
                </Spin>
                <div style="height: 337px; width: 100%" ref="container2"></div>
            </i-col>
        </Row>
        <Row :gutter="16" style="margin-top: 15px">
            <i-col span="24">
                <Card dis-hover >
                    <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！"
                           :data="infos" highlight-row stripe size="small" show-summary sum-text="合计"></Table>
                </Card>
            </i-col>
        </Row>
        <Modal v-model="modal2" width="1200" :mask-closable="false" title="安全生产费用各公司投入">
            <Table ref='table' style="margin-top: 10px" :loading="loading2" border :columns="columns2" no-data-text="没有查询到相关数据！"
                           :data="infos2" highlight-row stripe size="small" show-summary sum-text="合计"></Table>
            <div slot="footer">
                <Button @click="modal2 = false" class="ivu-btn-save" >关闭</Button>
            </div>
        </Modal>
    </div>
</template>

<script>

    import {sessionStorage} from '@/common/cacheUtils.js';
    import {Api} from '../../../api'
    import echarts from 'echarts';
    let cascaderDom = () => import('@/components/cascader-dom.vue');

    export default {
        name: "safetyProductionAnalysis2",
        components: {cascaderDom },
        data(){
            return{
                modal2: false,
                isSpin1: false,
                isSpin2: false,
                isSpin3: false,
                formInline: { inputYear: new Date(),  
                              orgId: sessionStorage('userId').getObject('userId').companyId,
                              orgName: sessionStorage('userId').getObject('userId').companyName },
                userInfo: sessionStorage('userId').getObject('userId'),
                loading2: false,
                loading: false,
                columns: [
                    {
                        title: '项目',
                        align: 'center',
                        key: 'codingName',
                        minWidth: 160,
                        fixed: 'left',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '12px'
                                    },
                                    on: {
                                        click: () => {
                                            this.modal2 = true;
                                            this.queryCompany();
                                        }
                                    }
                                }, params.row.codingName),
                            ]);
                        }
                    },
                    {
                        title: '一月',
                        align: 'center',
                        key: 'january',
                        minWidth: 80,
                    },
                    {
                        title: '二月',
                        align: 'center',
                        key: 'february',
                        minWidth: 80,
                    },
                    {
                        title: '三月',
                        align: 'center',
                        key: 'march',
                        minWidth: 80,
                    },
                    {
                        title: '四月',
                        align: 'center',
                        key: 'april',
                        minWidth: 80,
                    },
                    {
                        title: '五月',
                        align: 'center',
                        key: 'may',
                        minWidth: 80,
                    },
                    {
                        title: '六月',
                        align: 'center',
                        key: 'june',
                        minWidth: 80,
                    },
                    {
                        title: '七月',
                        align: 'center',
                        key: 'july',
                        minWidth: 80,
                    },
                    {
                        title: '八月',
                        align: 'center',
                        key: 'august',
                        minWidth: 80,
                    },
                    {
                        title: '九月',
                        align: 'center',
                        key: 'september',
                        minWidth: 80,
                    },
                    {
                        title: '十月',
                        align: 'center',
                        key: 'october',
                        minWidth: 80,
                    },
                    {
                        title: '十一月',
                        align: 'center',
                        key: 'november',
                        minWidth: 80,
                    },
                    {
                        title: '十二月',
                        align: 'center',
                        key: 'december',
                        minWidth: 80,
                    },
                    {
                        title: '合计',
                        align: 'center',
                        key: 'total',
                        fixed: 'right',
                        minWidth: 80,
                        render:(h,params)=>{
                            return h('div',[
                                h('span', Number(params.row.total))
                            ]);
                        }
                    },
                ],
                infos: [],
                infos2: [],
                twoLevelOrgList: [],
                sumData:{
                    fiveYear: '',
                    nowYear: ''
                },
                columns2:[
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '公司名称',
                        align: 'center',
                        key: 'orgName',
                        minWidth: 200,
                    },
                    {
                        title: '1月（万元）',
                        align: 'center',
                        key: 'january',
                        minWidth: 120,
                    },
                    {
                        title: '2月（万元）',
                        align: 'center',
                        key: 'february',
                        minWidth: 120,
                    },
                    {
                        title: '3月（万元）',
                        align: 'center',
                        key: 'march',
                        minWidth: 120,
                    },
                    {
                        title: '4月（万元）',
                        align: 'center',
                        key: 'april',
                        minWidth: 120,
                    },
                    {
                        title: '5月（万元）',
                        align: 'center',
                        key: 'may',
                        minWidth: 120,
                    },
                    {
                        title: '6月（万元）',
                        align: 'center',
                        key: 'june',
                        minWidth: 120,
                    },
                    {
                        title: '7月（万元）',
                        align: 'center',
                        key: 'july',
                        minWidth: 120,
                    },
                    {
                        title: '8月（万元）',
                        align: 'center',
                        key: 'august',
                        minWidth: 120,
                    },
                    {
                        title: '9月（万元）',
                        align: 'center',
                        key: 'september',
                        minWidth: 120,
                    },
                    {
                        title: '10月（万元）',
                        align: 'center',
                        key: 'october',
                        minWidth: 120,
                    },
                    {
                        title: '11月（万元）',
                        align: 'center',
                        key: 'november',
                        minWidth: 120,
                    },
                    {
                        title: '12月（万元）',
                        align: 'center',
                        key: 'december',
                        minWidth: 120,
                    },
                    {
                        title: '合计',
                        align: 'center',
                        key: 'total',
                        minWidth: 120,
                    },
                ],
            }
        },
        mounted(){
            // this.$refs.queryOrgCascader1.setCurrentOrg();
            this.queryAll();
        },
        methods: {
			reset1(){
				this.formInline= { 
					inputYear: new Date(),  
                    orgId: sessionStorage('userId').getObject('userId').companyId,
                    orgName: sessionStorage('userId').getObject('userId').companyName
			    }
				this.$refs.queryOrgCascader.setCurrentOrg()
				this.queryAll();
			},
            queryAll(){
                this.query();
                this.loadingChart1();
                this.loadingChart2();
                this.queryYearTotal();
            },
            query(){
                let data = {
                    orgId: this.formInline.orgId,
                };
                this.formInline.year = new Date(this.formInline.inputYear).getFullYear();
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.loading = true;
                this.$http.get(Api.safetyProduction+ '/statistics', {
                    params: data
                }).then(function(res){
                    this.infos = res.data.data;
                    this.loading = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            queryYearTotal(){
                let data = {
                    orgId: this.formInline.orgId,
                };
                this.formInline.year = new Date(this.formInline.inputYear).getFullYear();
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.safetyProduction+ '/company/year/total', {
                    params: data
                }).then(function(res){
                    this.sumData = res.data.data;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            loadingChart1(){
                let option = this.getOption1();
                let container = echarts.init(this.$refs.container1);
                this.isSpin1 = true;
                this.$http.get(Api.safetyProduction+ '/company/twoYear', {
                    params: {
                        orgId: this.formInline.orgId,
                        year: new Date(this.formInline.inputYear).getFullYear()
                    }
                }).then(function(res){
                    res.data.data.nowYear.forEach(i=>{
						// unshift  remark  .codingName
                        option.xAxis.data.push(i.codingName);
                        option.series[1].data.push(i.total);
                    });
                    res.data.data.lastYear.forEach(i=>{
                        option.series[0].data.push(i.total);
                    });
                    this.isSpin1 = false;
                    container.setOption(option);
                }, function(res){
                    this.$Message.error('请求失败');
                    this.isSpin1 = false;
                });
            },
            loadingChart2(){
                let option = this.getOption2();
                let container = echarts.init(this.$refs.container2);
                this.isSpin2 = true;
                this.$http.get(Api.safetyProduction+ '/company/month/total', {
                    params: {
                        orgId: this.formInline.orgId,
                        year: new Date(this.formInline.inputYear).getFullYear()
                    }
                }).then(function(res){
                    if(res.data.data == null){
                        option.series[0].data = [];
                    }else{
                        let year = new Date(this.formInline.inputYear).getFullYear()
                        let data = res.data.data.data;
                        let lastData = res.data.data.lastData;
                        let last2Data = res.data.data.last2Data;
                        option.series[0].name = year;
                        option.series[0].data = [data.january, data.february, data.march, data.april, data.may, data.june, data.july, data.august, data.september, data.october, data.november, data.december,];
                        option.series[1].name = year - 1;
                        option.series[1].data = [lastData.january, lastData.february, lastData.march, lastData.april, lastData.may, lastData.june, lastData.july, lastData.august, lastData.september, lastData.october, lastData.november, lastData.december,];
                        option.series[2].name = year - 2;
                        option.series[2].data = [last2Data.january, last2Data.february, last2Data.march, last2Data.april, last2Data.may, last2Data.june, last2Data.july, last2Data.august, last2Data.september, last2Data.october, last2Data.november, last2Data.december,];                    
                    }
                    container.setOption(option);
                    this.isSpin2 = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            queryTwoLevelOrg(){
                this.$http.get(Api.twoPlusFourReceipt + '/twoLevelOrg').then((res) => {
                    if(res.data.status == 200){
                        this.twoLevelOrgList = res.data.data;
                    }
                }).catch(e => {
                    this.$Message.error("数据查询失败");
                });
            },
            getOption1(){
                return {
                    title: {
                        text: '投入项目（万元）'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                    },
                    legend: {},
                    color: ['#1999FF', '#EEB422'],
                    // dataZoom: [
                    //     {
                    //         type: 'slider',
                    //         yAxisIndex: 0,
                    //         zoomLock: true,
                    //         width: 10,
                    //         right: 10,
                    //         top: 70,
                    //         bottom: 20,
                    //         start: 85,
                    //         end: 100,
                    //         handleSize: 0,
                    //         showDetail: false
                    //     },
                    //     {
                    //         type: 'inside',
                    //         id: 'insideY',
                    //         yAxisIndex: 0,
                    //         start: 85,
                    //         end: 100,
                    //         zoomOnMouseWheel: false,
                    //         moveOnMouseMove: true,
                    //         moveOnMouseWheel: true
                    //     }
                    // ],
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: [],
                        splitLine: {show: false},
                        axisLabel: {
                            interval: 0,
                            formatter: function (value) {
								return value.substr(1,2).replace('）','')
                                // let str = "";
                                // let num = 6; //每行显示字数
                                // let valLength = value.length; //该项x轴字数
                                // let rowNum = Math.ceil(valLength / num); // 行数
                                // if (rowNum > 1) {
                                //     for (let i = 0; i < rowNum; i++) {
                                //         let temp = "";
                                //         let start = i * num;
                                //         let end = start + num;
                                //         temp = value.substring(start, end) + "\n";
                                //         str += temp;
                                //     }
                                //     return str;
                                // } else {
                                //     return value;
                                // }
                            }
                        }
                    },
                    yAxis: {
						type: 'value',
						boundaryGap: [0, 0.01],
						splitLine: {show: false},
                        
                    },
                    series: [
                        {
                            name: '上年度',
                            type: 'bar',
                            data: []
                        },
                        {
                            name: '本年度',
                            type: 'bar',
                            data: []
                        }
                    ]
                };
            },
            getOption2(){
                return {
                    title: {
                        text: '月度投入（万元）'
                    },
                    grid:{
                        bottom: '9%',
                        left: '15%',
                        right: 0
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                    },
                    legend: {},
                    xAxis: {
                        type: 'category',
                        data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                        boundaryGap: false,
                    },
                    color: ['#1999FF', '#EEB422', '#CCFF33'],
                    yAxis: {
                        type: 'value',
                        splitLine: {show: false},

                    },
                    series: [
                        {
                            name: '',
                            data: [],
                            type: 'line'
                        },
                        {
                            name: '',
                            data: [],
                            type: 'line'
                        },
                        {
                            name: '',
                            data: [],
                            type: 'line'
                        }
                    ]
                };
            },
            queryCompany(){
                let data = {
                    orgId: this.formInline.orgId,
                };
                this.loading2 = true;
                this.formInline.year = new Date(this.formInline.inputYear).getFullYear();
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.safetyProduction+ '/company', {
                    params: data
                }).then(function(res){
                    this.infos2 = res.data.data;
                    this.loading2 = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            exportExcel(){
                let data = {
                    orgId: this.userInfo.twoLevelOrgId != null ? this.userInfo.twoLevelOrgId: this.userInfo.companyId,
                };
                this.formInline.year = new Date(this.formInline.inputYear).getFullYear();
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.isSpin3 = true;
                this.$http.get(Api.safetyProduction + '/statistics/export',{
                    params: data,
                    responseType: 'arraybuffer'
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "安全投入统计表.xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                    this.isSpin3 = false;
                }, function(res){
                    this.$Message.error('生成失败');
                })
            },
            setOrgId(data){
                this.formInline.orgId = data[data.length - 1];
            }
        }
    }
</script>

<style  lang='css' scoped>
    @import '../../../index.css';

    .safety_title {
        color: white;
        font-weight: bold;
        width: 100%;
        height: 100%;
        background: url('../../../assets/bbmg/safe/safetyProduction_title.png') no-repeat;
        background-repeat: no-repeat;
        background-position: -16px, -10%;
        background-size: 112%, 112%;
    }

    .demo-spin-icon-load {
        animation: ani-demo-spin 1s linear infinite;
    }

    @keyframes ani-demo-spin {
        from {
            transform: rotate(0deg);
        }
        50% {
            transform: rotate(180deg);
        }
        to {
            transform: rotate(360deg);
        }
    }
</style>
